package com.itheima.mq;

import com.itheima.utils.RedisUtil;
import com.itheima.utils.SmsUtil;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class SmsConsumer implements InitializingBean {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    //如果监听到就赋值给telephone
    @RabbitListener(queues = "sms_queue")
    public void recv(String telephone){
        //调用工具
        try {
            String code = SmsUtil.sendSmsCode();
            System.out.println("模拟验证码为（code）:"+code);
            //存放到redis中去
            RedisUtil.set("sms:"+telephone,code,1L, TimeUnit.MINUTES);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //实现InitializingBean接口，实现afterPropertiesSet（）方法，这个方法只加载一次。
        @Override
        public void afterPropertiesSet() throws Exception {
            RedisUtil.register(redisTemplate);
    }
}
